﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections.Concurrent;
using Newtonsoft.Json;



    public class Client
    {
        public bool canRead=false;
        
        private static Socket socket;
        static ReceiveDataUnpack messageHandle= new ReceiveDataUnpack();
        
        static Data data=new Data();
        private static Message message;
        static ConcurrentQueue<String> concurrentQueue = new ConcurrentQueue<String>();
        public Data Data
        {
            get{ return data; }
        }

        public Message Message
        {
            set{ message=value; }
        }

        public void Connect(String ip, int port)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress address = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(address, port);
            socket.Connect(endPoint);
        }

        public void Send(Data InData)
        {
            string jsonData = JsonConvert.SerializeObject(InData);
            concurrentQueue.Enqueue(jsonData);

                Thread.Sleep(5);
                if(!concurrentQueue.IsEmpty)
                {
                    concurrentQueue.TryDequeue(out String message);
                    socket.Send (TCPpackage.wrap(message));
                }
        }

        public void StartReceiveThread()
        {
            Thread receiveMessage= new Thread(Receive);
            receiveMessage.Start();

        }
        public void ShutDown()
        {
            socket.Shutdown(SocketShutdown.Both);
        }
        public void Close()
        {
            socket.Close();
        }
        
        private void Receive()
        {
            while (true)
            {
                try
                {
                    int dataNum =socket.Receive(messageHandle.DataBuffer);
                    messageHandle.ReadMessage(dataNum);
                }
                catch (Exception e)
                {

                }
                if (messageHandle.isRead)
                {
                    data = JsonConvert.DeserializeObject<Data>(messageHandle.ReceiveStr);
                    message.SetData(data);
                }
                
            }
        }

    }
